CLIENT = $$(readlink -f client)
SERVER = $$(readlink -f server)
MAKE = make
KS_PYPI_HOST = pypi.intra.knownsec.com
KS_PYPI = http://$(KS_PYPI_HOST)/testuser/dev
KS_PYPI_WHL = "http://$(PYPI_USERNAME):$(PYPI_PASSWORD)@$(KS_PYPI_HOST)/websoc/pypi"

.PHONY: all install lint run_ui run_server sdist

all:
	make install
	make lint
	make test
	make clean

install:
	make install_ui
	make install_server

test:
	make test_ui
	make test_server

install_ui:
	npm --version
	yarn --version
	cd $(CLIENT); \
		yarn install;

install_server:
	pip --version
	cd $(SERVER); \
		pip install -e .[dev,build] -i $(KS_PYPI) --trusted-host $(KS_PYPI_HOST) ;

install_wheel:
	cd $(SERVER); \
		pip install -e .[dev,crypt] --find-links /var/lib/local-pip-index/ -i $(KS_PYPI_WHL) --trusted-host $(KS_PYPI_HOST) ;

test_server:

test_ui:
	cd $(CLIENT); \
		yarn test;

lint:
	if type flake8 ; then \
		find $(SERVER) -type f -name '*.py' -print0 | xargs -0 flake8 ; \
	fi
	if type mypy ; then \
		mypy --install-types --non-interactive $(SERVER) || mypy $(SERVER) ; \
	fi

run_ui:
	cd $(CLIENT) && yarn start

run_server:
	cd $(SERVER) && python3 wassui/manage.py runserver 0.0.0.0:$(PORT)

uidist:
	cd $(CLIENT); \
		rm -rf dist; \
		yarn; \
		yarn build; \
		tar -zcvf wassui-$(CI_COMMIT_TAG).tar.gz dist; \
		curl -k -T wassui-$(CI_COMMIT_TAG).tar.gz $(RELEASE_SITE)/wassui-$(CI_COMMIT_TAG).tar.gz -u $(RELEASE_SITE_USERNAME):$(RELEASE_SITE_PASSWORD);

sdist:
	make install_server
	cd $(SERVER); \
		rm -rf dist; \
		devpi use $(KS_PYPI); \
		devpi login testuser --password ''; \
		devpi upload;

bdist_wheel:
	rm -rf dist
	cd $(SERVER) && python3 -m pip install -e .[build] -i $(KS_PYPI_WHL) --trusted-host $(KS_PYPI_HOST)
	find $(SERVER) -name '*.py' | grep -v "$(SERVER)/wassui/__init__.py\|$(SERVER)/setup.py\|management/commands" | xargs python3 -OO -m pyshield -r -D
	cd $(SERVER) && python3 setup.py bdist_wheel && devpi use $(KS_PYPI_WHL) && devpi login $(DEVPI_USERNAME) --password $(DEVPI_PASSWORD) && devpi upload dist/*.whl

clean:
	rm -rf *.egg-info dist build __pycache__ .tox
	find $(SERVER) -type f -name '*.pyc' -delete || true
	find $(SERVER) -type d \( -name '.mypy_cache' -o -name '__pycache__' \) -exec rm -r "{}" \; || true

format:
	pip install black -i $(KS_PYPI) --trusted-host $(KS_PYPI_HOST)
	black -S $(SERVER)
